//
// Created by xiaoma on 1/27/21.
//
#include "BufferedInputStream.h"

BufferedInputStream::BufferedInputStream(const char *fileName) {
    fp = fopen(fileName, "rb");

    fread(buffer, BUFFER_LEN * sizeof(char), 1, fp);
    index = 0;
}

BufferedInputStream::~BufferedInputStream() {
    if (fp) {
        fclose(fp);
        fp = nullptr;
    }
}

char BufferedInputStream::read() {
    if (index >= BUFFER_LEN) {
        index = 0;
        fread(buffer, BUFFER_LEN * sizeof(char), 1, fp);
    }
    return buffer[index++];
}

int BufferedInputStream::readInt() {
    int b1 = read() & 0xff;
    int b2 = read() & 0xff;
    int b3 = read() & 0xff;
    int b4 = read() & 0xff;

    return b4 << 24 | b3 << 16 | b2 << 8 | b1;
}

void BufferedInputStream::unread() {
    if (index > 0) {
        index++;
    }
}